<?php
namespace app\admin\controller;
use think\Controller;
class Common extends Controller{
	public function _initialize(){
		if(!session('id') && !session('name')){
			$this -> redirect('login/login');
		}
		$this -> check();
	}
	public function check(){
		# 获取当前模型的控制器/方法
		$name = strtolower(request() -> controller() .'/'. request() -> action());
		$id = session('id');
		# 获取用户的权限规则
		$ruleCheck = $this -> getRuleCheck($id);
//		dump($name);dump($ruleCheck);die;
		# 如果是顶级管理员则不用判断
		// if($id != 1){
			if(!in_array($name,['index/index'])){
				if(!in_array($name,$ruleCheck)){
					$this -> error('您没有权限','index/index');
				}
			}
		// }
	}
	public function getRuleCheck($id){
		$adminRes = db('admin') 
            -> alias('t1')     
            // -> field('t1.id,t1.name,t2.title,t2.rules')
            -> field('t2.rules')
            -> join('bk_rbac_group t2','t1.gid = t2.id')
            -> where('t1.id = '. $id)
            -> find();
        $ruleRes = db('rbac_rule') -> where('id','in',$adminRes['rules']) -> select();
        $ruleCheck = [];
        foreach($ruleRes as $val){
        	$ruleCheck[] = preg_replace('/(\s)|_/','',strtolower($val['name']));
        	// $ruleCheck[] = str_replace('_','',strtolower($val['name']));
        }
        return $ruleCheck;
	}
}